<template>
	<view class="chat-container pos-rel">
		<!-- 留言 -->
		<view class="main-header flex align-end	" v-if="chat_counselor">
			<navigator 
				:url="'/pages/consult/detail?id='+chat_counselor.id" 
				hover-class="none"
				class="font-size-15 header-title" >
				<text class="font-color-normal font-size-18 font-bold"> {{chat_counselor.counselor_name}} </text>为您服务
			</navigator>
			<text class="online-status" v-if="chat_counselor.counselor_online == 1">• 在线</text>
			<text class="notonline-status" v-else>• 离线</text>
		</view>
		<!-- 内容 -->
		<view class="content-wrapper">
			<view class="chat-wrapper">
				<scroll-view
					@scrolltoupper="scrollTop"
					id="kefu_scroll"
					:scroll-y="true"
					:scroll-with-animation="kefu_scroll_with_animation"
					:scroll-top="kefu_scroll_top"
				>
					<view class="container pad-t-10 pad-b-20" >
						<view class="chat-system pos-rel text-center" v-if="index_page>=total_page">
							<text class="time">很高兴为您服务</text>
						</view>
						<block v-for="(item,index) in record_msg" :key="index">
							<!-- <view class="chat-system pos-rel text-center">
								<text class="time">05-19 16:25</text>
							</view> -->
							<view class="chat-me flex pad-l-20 justify-end text-right" v-if="item.sender_id == user_info.id">
								<view class="chat-info flex-1 mar-r-15">
									<view class="font-color-999 font-size-12">
										<text>{{item.nickname}}</text>
									</view>
									<view class="chat-text dis-inline-block pos-rel">
										<text>{{item.message}}</text>
									</view>
								</view>
								<view class="user-image pos-rel">
									<image :src="item.avatar"></image>
								</view>
							</view>
							<view class="chat-you flex pad-r-20" v-else>
								<view class="user-image pos-rel">
									<image :src="item.avatar"></image>
								</view>
								<view class="chat-info flex-1 mar-l-15">
									<view class="font-color-999 font-size-12">
										<text>{{item.nickname}}</text>
									</view>
									<view class="chat-text dis-inline-block pos-rel">
										<text>{{item.message}}</text>
									</view>
								</view>
							</view>

						
						</block>
					</view>
					
					<!-- <block v-for="(item,index) in record_msg" :key="index">
						<view class="bubble me" v-if="item.sender_id == user_info.id">
							<text>{{item.message}}</text>
							<text class="kefu_message_status kefu_message_51513">未读</text>
						</view>
						<view class="bubble you" v-else>
							<text>{{item.message}}</text>
							<text class="kefu_message_status kefu_message_51513" v-if="item.status==0">未读</text>
						</view>
					</block>-->
				</scroll-view>
			</view>
		</view>
		<view class="write flex">
			<view class="flex-1">
				<textarea id="message" spellcheck="false" style="height: 35px;" v-model="message"></textarea>
			</view>
			<view class="">
				<button class="send-btn dis-inline-block" @click="sendMsg">发送</button>
			</view>
		</view>
	</view>
</template>

<script>
import { userAdSession, getUserSessionById,userMsgBySessionId, userSendMsg } from '@/utils/http'
import {socketurl} from '@/common/config'
export default {
	data() {
		return {
			order_no: '',
			// session_id: '',
			message: '', //发送消息
			record_msg: [],
			index_page: 0,
			total_page: 1,
			kefu_scroll_with_animation: false,
			kefu_scroll_top: 0,
			chat_counselor:''
		}
	},
	computed: {
		user_info() {
			return this.store.state.user_info
		},
		session_id(){
			return this.store.state.session_id
		}
		// record_msg() {
		// 	return this.store.state.msg_list[this.session_id]
		// }
	},
	methods: {
		//加载更多历史聊天记录
		scrollTop() {
			if (this.index_page < this.total_page) {
				this.getHistoryMsg()
			} else {
				this.errorToShow('没有更多')
			}
		},
		//滚动操作
		scrollIntoFooter: function(timeout = 0, kefu_scroll_top = 0) {
			var that = this
			if (kefu_scroll_top) {
				setTimeout(function() {
					that.kefu_scroll_top =
						that.kefu_scroll_top > 99990
							? that.kefu_scroll_top + 200
							: kefu_scroll_top
				}, timeout)
				return
			}
			let kefu_scroll = uni.createSelectorQuery().select('#kefu_scroll')
			kefu_scroll
				.fields({ scrollOffset: true }, data => {
					setTimeout(function() {
						that.kefu_scroll_top = data.scrollHeight
					}, timeout)
				})
				.exec()
		},
		// 滚动操作结束
		//获取聊天记录
		getHistoryMsg() {
			if(!this.session_id) return;
			userMsgBySessionId({
				session_id: this.session_id,
				page: this.index_page + 1
			}).then(res => {
				if (res) {
					this.index_page = res.current_page
					this.total_page = res.last_page
					// res.session_id = this.session_id
					let msgs = res.data
					msgs.sort(function(a, b) {
						return a['id'] - b['id']
					})
					if (res.current_page == 1) {
						this.record_msg = [...this.record_msg, ...res.data]
						this.scrollIntoFooter()
					} else {
						this.record_msg = [...res.data, ...this.record_msg]
						this.scrollIntoFooter(0, 60)
					}
				}
			})
		},
		//根据订单创建一条会话
		async createRecordSession() {
			await userAdSession({
				order_no: this.order_no
			}).then(res => {
				if(res){
					this.$store.dispatch('set_session_id', res.id);
					// this.session_id = res.id
					this.chat_counselor = res
				}
				
			})
		},
		//根据session_id 获取会话
		async createRecordByid(session_id){
			await getUserSessionById({
				session_id
			}).then(res=>{
				if(res){
					console.log(123);
					this.$store.dispatch('set_session_id', res.id);
					// this.session_id = res.id
					this.chat_counselor = res
				}
			})
		},
		//处理聊天消息
		chat_record(msg) {
			if (msg.session_id == this.session_id) {
				this.message = "";
				this.record_msg.push(msg)
				this.scrollIntoFooter()		
			}
			
		},
		//发送消息
		sendMsg() {
			if( this.message !=''){
				let msg = {
					type: 'chat_record',
					message: this.message,
					session_id: this.session_id,
					avatar: this.user_info.avatar,
					nickname: this.user_info.nickname,
					sender_id: this.user_info.id
				}
				userSendMsg(msg).then(res => {
					this.chat_record(msg)
					
				})
			}
			
		},
		//处理上线提醒
		login_notice(msg){
			console.log('处理上线提醒');
			console.log(msg);
			if(msg.user_id == this.chat_counselor.counselor_uid){
				this.chat_counselor.counselor_online = 1;
			}
		},
		//处理上线提醒
		logout_notice(msg){
			if(msg.user_id == this.chat_counselor.counselor_uid){
				this.chat_counselor.counselor_online = 0;
			}
		},
		//监听聊天
		onMessage() {
			// 收到消息
			let _that = this
			if (
				this.store.state.socketTask &&
				this.store.state.is_open_socket
			) {
				uni.onSocketMessage(function(res) {
					
					let msg = JSON.parse(res.data)
					console.log(123+msg.type);
					try {
						if (_that[msg.type]) {
							_that[msg.type].call(this, msg)
						}
					} catch (error) {
						_that.common.errorToShow(error.msg)
					}
				})
			}
		}
	},

	async onLoad() {
	
		const session_id = this.options.session_id || '';
		await this.createRecordByid(session_id);
		console.log(456);
		this.getHistoryMsg()
		this.onMessage()
		this.$store.commit('clear_session_record',this.session_id);
		//清除本地会话记录
		//this.kefu_scroll_top = 245
		//console.log(window.top)
	},
	onUnload() {
		this.$store.dispatch('set_session_id', null);
		this.$store.commit('reset_max_reter_count');
		this.$store.commit('retry_websocket',socketurl)
		// if (this.ws.SocketTask && this.ws.socketOpen) {
		// 	console.log('页面卸载主动关闭链接')
		// 	this.ws.unloadCloseWs = true
		// 	uni.closeSocket()
		// }
	}
}
</script>

<style scoped>

</style>